package com.code2roc.fastboot.system.setting.service.impl;

import com.code2roc.fastboot.system.setting.model.SystemGroupDO;
import com.code2roc.fastboot.system.setting.service.ISystemGroupService;
import com.code2roc.fastboot.model.BaseBootServiceImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SystemGroupServiceImpl extends BaseBootServiceImpl<SystemGroupDO> implements ISystemGroupService {
    @Override
    public boolean checkExistSub(String parent_id) {
        String sql = "parent_id = #{parent_id}";
        HashMap paramMap = new HashMap();
        paramMap.put("parent_id", parent_id);
        return selectCount(sql, paramMap) > 0;
    }

    @Override
    public List<String> getAllSubGroupIDList(String group_id) {
        List<String> guidlist = new ArrayList<String>();
        guidlist.add(group_id);
        List<SystemGroupDO> lst_All = selectAllList();
        selectSubList(lst_All, group_id, guidlist);
        return guidlist.stream().distinct().collect(Collectors.toList());
    }

    @Override
    public String getGroupIDSearchSQL(String group_id) {
        String guidString = "";
        List<String> guidList = getAllSubGroupIDList(group_id).stream().distinct().collect(Collectors.toList());
        if (guidList.size() == 0) {
            guidString = "''";
        } else {
            for (int i = 0 ; i < guidList.size(); i++) {
                if(i==guidList.size()-1){
                    guidString += "'"+guidList.get(i)+"'";
                }else{
                    guidString += "'"+guidList.get(i)+"',";
                }
            }
        }
        return " and group_id in ("+guidString+")";
    }

    private void selectSubList(List<SystemGroupDO> lst_All, String parent_id, List<String> guidList) {
        List<SystemGroupDO> list = lst_All.stream().filter((SystemGroupDO f) -> f.getParent_id().equals(parent_id)).collect(Collectors.toList());
        if (list.size() > 0) {
            for (SystemGroupDO entity : list) {
                guidList.add(entity.getRow_id());
                selectSubList(lst_All, entity.getRow_id(), guidList);
            }
        }
    }
}
